const util = require('../../utils/util');
const ConfigService = require('../../service/system/config.service');

async function listConfigs(ctx) {
	const { configName = '', page = 1, limit = 10 } = ctx.query;

	try {
		const result = await ConfigService.listConfigs({
			configName,
			page: +page,
			limit: +limit,
		});
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `查询参数列表失败: ${error.message}`);
	}
}

async function saveConfig(ctx) {
	const { userId } = util.decodeToken(ctx);
	const { id, configName, configKey, configValue, remark } = ctx.request.body;

	if (!configName || !configKey || !configValue) {
		return util.fail(ctx, '参数名、键或值不能为空');
	}

	try {
		const result = await ConfigService.saveConfig({
			id: id || null,
			configName,
			configKey,
			configValue,
			remark: remark || '',
			userId,
		});
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `保存参数失败: ${error.message}`);
	}
}

async function deleteConfigs(ctx) {
	const { ids } = ctx.request.body;

	if (!Array.isArray(ids) || ids.length === 0) {
		return util.fail(ctx, '参数 ID 无效');
	}

	try {
		const result = await ConfigService.deleteConfigs(ids);
		util.success(ctx, { ids });
	} catch (error) {
		util.fail(ctx, `删除参数失败: ${error.message}`);
	}
}

module.exports = { listConfigs, saveConfig, deleteConfigs };
